<?php
/**
 * API基类Controller
 *
 * User: Jay
 * Date: 2018/7/24
 */

namespace ApiBundle\Controller;

use BaseBundle\Controller\BaseController;

class ApiController extends BaseController
{
    /**
     * 入口方法
     *
     * @param $return_type
     * @param bool $is_login 是否强制登陆
     * @return bool
     * @throws \Exception
     */
    public function inlet($return_type, $is_login = true)
    {
        if(($r = parent::inlet($return_type, $is_login)) !== true){
            return $r;
        }

        if(empty($this->getPlatform())){
            if(empty(self::$request->get($this->getParameter('param_platform')))){
                return $this->response($this->getParameter('param_platform') . '不能为空');
            }

            $this->setPlatform(self::$request->get($this->getParameter('param_platform')));
        }

        if(in_array($this->getPlatform(), [$this->getParameter('platform_android'), $this->getParameter('platform_ios')])){
            if(empty(self::$request->get($this->getParameter('param_version')))){
                return $this->response($this->getParameter('param_version') . '不能为空');
            }
        }

        // TODO 业务代码

        return true;
    }

    /**
     * 调用其他bundle数据
     *
     * @param $BundleControllerAction
     * @param array $path
     * @param string $return_type
     * @return mixed
     */
    public function getApiData($BundleControllerAction, array $path = array(), $return_type = 'page')
    {
        $bundle_info = $this->forward($BundleControllerAction, $path)->getContent();

        $data = json_decode($bundle_info, TRUE);

        if (!is_array($data)) {
            exit($bundle_info);
        }

        if ($return_type == $this->getParameter('return_page')) {
            if ($data['errorCode'] == $this->getParameter('error_code_not_logged')) {
                return $this->redirect($data['data']['go_url'], 301);
            }

            if ($data['errorCode'] == $this->getParameter('error_code_failure')) {
                $this->ex($data['message']['message']);
            }
        }

        return $data;
    }

    /**
     * 获取app版本
     *
     * @param string $version
     * @return mixed
     */
    protected function getAppVersion($version = '')
    {
        if(empty($version)){
            $version = self::$request->get($this->getParameter('param_version'));
        }

        return end(explode('.', $version));
    }
}